<?php
  defined('_JEXEC') or die();
  jimport('joomla.application.component.model');
  require_once('base.php');
  
  class PicModelPic extends BaseModel
  {     
    var $_name        = "pic";
    var $_table       = "#__pbny_pics";
    
    function save($data){
        
      $this->before_save($data);
        
      $row =& $this->getTable($this->_name);            
           
      if (!$row->bind($data)) 
      {
        JError::raiseError(500, 'Error binding data');              
      }     
       
      if (!$row->check()) 
      {
        JError::raiseError(500, 'Invalid data');                           
      }
       
            if (!$row->store()) 
      {
        $errorMessage = $row->getError();
        JError::raiseError(500, 'Error binding data: '.$errorMessage);                           
      }
      
      return $row;
    }
  
    function get_pic_types(){
      
      $query = "SHOW COLUMNS FROM ".$this->_table." WHERE field = 'pic_type'";
      $db = $this->getDBO();
      $db->setQuery($query);
      $row = $db->loadRow();
      
      $result = str_replace(array("enum(",")","'"),"",$row[1]);
      return explode(",",$result);
    }
    
    function get_pic_type_instance($pic_type, $id){
      
      $result = null;
      
      switch($pic_type){
        case "SEASONS":
          $season   = $this->getInstance('season', 'seasonmodel');
          $s      = $season->get($id);
          
          if($s)
            $result = $s->name;
        break;
        case "TEAMS":
          $team     = $this->getInstance('team', 'teammodel');
          $t        = $team->get($id);
          
          if($t)
            $result = $t->name;
      
        break;
        case "PLAYERS":
          $player   = $this->getInstance('player', 'playermodel');
          $person   = $this->getInstance('person', 'personmodel');
          
          $p      = $player->get($id);
          if($p)
            $result = $person->get_fullname($p->person_id);
          
        break;
        case "VENUES":
          $venue   = $this->getInstance('venue', 'venuemodel');
          $v     = $venue->get($id);
          
          if($v)
            $result = $v->name;
          
        break;
        case "GAMES":
          $team       = $this->getInstance('team', 'teammodel');
          $schedule   = $this->getInstance('schedule', 'schedulemodel');
          $s          = $schedule->get($id);
          
          if($s){
            $t = $team->get($s->first_team_id);
            $t2 = $team->get($s->second_team_id);
            $text = "$t->name VS. $t2->name ".strftime('%Y-%m-%d %H:%M',strtotime($s->schedule));
            $result = $text;
          }
        break;
      }
      
      return $result;
    }
    
    function get_pic_type_instances($pic_type){
      
      $data = array();
      
      switch($pic_type){
        case "SEASONS":
          $season   = $this->getInstance('season', 'seasonmodel');
          $seasons  = $season->get();
          
          if($seasons){
            foreach($seasons as $s)
              $data[$s->id] = $s->name;
          }
        break;
        case "TEAMS":
          $team   = $this->getInstance('team', 'teammodel');
          $teams  = $team->get();
          
          if($teams){
            foreach($teams as $t)
              $data[$t->id] = $t->name;
          }
        break;
        case "PLAYERS":
          $player   = $this->getInstance('player', 'playermodel');
          $person   = $this->getInstance('person', 'personmodel');
          
          $players  = $player->get();
          if($players){
            foreach($players as $p)
              $data[$p->id] = $person->get_fullname($p->person_id);
          }
        break;
        case "VENUES":
          $venue   = $this->getInstance('venue', 'venuemodel');
          $venues  = $venue->get();
          
          if($venues){
            foreach($venues as $v)
              $data[$v->id] = $v->name;
          }
        break;
        case "GAMES":
          $team       = $this->getInstance('team', 'teammodel');
          $schedule   = $this->getInstance('schedule', 'schedulemodel');
          $schedules  = $schedule->get();
          
          if($schedules){
            foreach($schedules as $s){
              $t = $team->get($s->first_team_id);
              $t2 = $team->get($s->second_team_id);
              $text = "$t->name VS. $t2->name ".strftime('%Y-%m-%d %H:%M',strtotime($s->schedule));
              $data[$s->id] = $text;
            }
          }
        break;
      }
      return $data;
    }
    
    function get_pics_by_instance($pic_type, $id){
    
      $sql = 'SELECT * FROM '.$this->_table.
           " WHERE pic_type ='$pic_type' AND pic_id = $id";
      return $this->_get($sql);
    }
    
    function get_photo_gallery(){
      
      $sql = 'SELECT * FROM '.$this->_table.
             " WHERE pic_type in ('TEAMS','VENUES','SEASONS','GAMES')";
      return $this->_get($sql);
    }
  
    private function before_save(&$data){
      
	  // Get actual pic
	  $data['pic'] = PBNYHelper::downloadImage($data['pic_url']);
	
  	  if($data['url'] != $data['pic_url']){
	  
        $filename_components    = explode('/',$data['pic']);
        $filename_components[0] = JPATH_ROOT;
        $filename               = implode(DS, $filename_components);
      
        if(is_dir($filename))
          throw new Exception("Specified file is a directory.");
      
        $md5 = md5_file($filename);
        $data['md5']       = $md5;
        
        $sql = "SELECT flickr_id " .
               "FROM " . $this->_table .
             " WHERE md5 = '$md5' LIMIT 1";
      
        $result = $this->_get($sql, true);
        if(!$result)
          $data['flickr_id'] = PBNYHelper::sendImageToFlickr($filename);
		else
		  $data['flickr_id'] = $result->flickr_id;

	  }
	}
  }
?>